#!/usr/bin/python3
# _*_ coding: utf-8 _*_
#
# Copyright (C) 2024 - 2024 heihieyouheihei, Inc. All Rights Reserved 
#
# @Time    : 2024/8/23 22:46
# @Author  : Yuyun
# @File    : leetcode_206_反转链表.py
# @IDE     : PyCharm

'''
给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。

示例 1：
输入：head = [1,2,3,4,5]
输出：[5,4,3,2,1]

示例 2：
输入：head = [1,2]
输出：[2,1]

示例 3：
输入：head = []
输出：[]

提示：
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000

进阶：链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题？
'''

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class LinkList:
    def __init__(self, num_list=[]):
        self.dummy_head = ListNode()
        self.size = len(num_list)
        current = self.dummy_head
        #   根据列表新建链表
        for num in num_list:
            new_node = ListNode(num)
            current.next = new_node
            current = current.next
    def reverse_linklist(self):
        pre = None
        current = self.dummy_head.next
        while current != None:
            tmp = current.next
            current.next = pre
            #   pre向后移动，存储的反转后的链表
            pre = current
            #   current向后移动，反转前的链表剩余部分
            current = tmp
        self.dummy_head.next = pre

    def show_linklist(self):
        current = self.dummy_head.next
        while current != None:
            print(current.val, end=' ')
            current = current.next
        #   输出格式，必须换行
        print()

if __name__ == '__main__':
    while True:
        try:
            n, *num = list(map(int, input().split()))
            if n == 0:
                print("list is empty")
                #   此处必须用break，
                #   本人一开始用continue，一直报错“潜在的数组或指针越界，请检查代码。”，找了好久原因
                break
            linklist = LinkList(num)
            linklist.show_linklist()
            linklist.reverse_linklist()
            linklist.show_linklist()
        except:
            #   此处必须为break，换成打印异常输出的写法，结果会报错“输出超限”，找了半天原因
            break